package com.lagou.edu.service.impl;


import com.lagou.edu.config.EmailServerConfig;
import com.lagou.edu.service.EmailService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
public class EmailServiceImpl implements EmailService {
    private static final String SENDER_NAME = "lagou-email-service";

    @Autowired
    private EmailServerConfig emailServerConfig;

    @Override
    public Boolean send(String emailAddress, String code) {
        if (StringUtils.isEmpty(emailAddress) || StringUtils.isEmpty(code) ) {
            throw new RuntimeException("email or code is empty");
        }

        try {
            HtmlEmail email = new HtmlEmail();
            List<String> list = new ArrayList<String>();
            list.add(emailAddress);
            String[] receiverList = list.toArray(new String[list.size()]);

            email.setHostName(emailServerConfig.getHostname());
            email.setCharset("UTF-8");
            email.addTo(receiverList);
            email.setFrom(emailServerConfig.getUsername(), SENDER_NAME);
            email.setAuthentication(emailServerConfig.getUsername(), emailServerConfig.getPassword());
            email.setSubject("验证码");
            email.setHtmlMsg("您的验证码为:" + code + ".");

            String resultResult = email.send();
            System.out.println("邮件发送结果>>>" + resultResult);

        } catch (Exception e) {
            System.err.println("发送邮件发生异常>>>");
            e.printStackTrace();
            return false;
        }

        return true;
    }
}
